<template>
  <div>
    <div>
      <el-row v-show="!showEdit">
        <el-button type="primary" icon="Plus" @click="handleCreate"
          >新增
        </el-button>
      </el-row>
      <el-row v-show="showEdit">
        <el-button type="primary" icon="Back" @click="backTable"
          >返回
        </el-button>
        <el-button
          type="success"
          icon="Check"
          @click="submitForm"
          v-show="isEdit"
          >保存
        </el-button>
      </el-row>
    </div>
    <el-divider></el-divider>
    <div v-show="!showEdit">
      <el-form :inline="true" @submit.prevent>
        <el-form-item label="发券名称">
          <el-input
            v-model="query.couponDirectName"
            placeholder="请输入发券名称"
            @keyup.enter="currentChange(1)"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="currentChange(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div v-show="!showEdit">
      <el-table :data="tableData" row-key="couponDirectId" border stripe>
        <el-table-column type="index" label="序号" width="60">
        </el-table-column>
        <el-table-column
          prop="couponDirectName"
          label="发券名称"
          sortable
          width="180"
        >
        </el-table-column>
        <el-table-column prop="sendType" label="发放类型" width="120">
          <template #default="scope">
            <el-tag :type="'primary'">
              {{ scope.row.sendType === 1 ? "按标签" : "指定手机号" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="smsNotify" label="短信通知" width="100">
          <template #default="scope">
            {{ scope.row.smsNotify === 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="发放状态" width="100">
          <template #default="scope">
            <h3 v-if="scope.row.status == 0">
              <el-tag :type="'primary'">未开始</el-tag>
            </h3>
            <h3 v-if="scope.row.status == 1">
              <el-tag :type="'primary'">发送中</el-tag>
            </h3>
            <h3 v-if="scope.row.status == 2">
              <el-tag :type="'primary'">已完成</el-tag>
            </h3>
            <h3 v-if="scope.row.status == 3">
              <el-tag :type="'danger'">发送失败</el-tag>
            </h3>
          </template>
        </el-table-column>
        <el-table-column prop="createdName" label="创建人" width="100">
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createdTime"
          :formatter="formatTableColumnDate"
          width="180"
        >
        </el-table-column>
        <el-table-column prop="updatedName" label="修改人" width="100">
        </el-table-column>
        <el-table-column
          label="修改时间"
          prop="updatedTime"
          :formatter="formatTableColumnDate"
          width="180"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              icon="View"
              @click="handleView(scope.row)"
              v-show="scope.row.status > 0"
              >查看</el-button
            >
            <el-button
              size="small"
              icon="Check"
              @click="handleSendCoupon(scope.row)"
              v-show="scope.row.status == 0"
              >发放</el-button
            >
            <el-button
              size="small"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-show="scope.row.status == 0"
              >编辑</el-button
            >
            <el-button
              size="small"
              icon="Delete"
              type="danger"
              @click="handleDelete(scope.row)"
              v-show="scope.row.status == 0"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" class="row-bg" justify="end">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.current"
          :page-size="query.size"
          :total="query.total"
          @current-change="currentChange"
        >
        </el-pagination>
      </el-row>
    </div>

    <div v-show="showEdit">
      <el-tabs type="border-card">
        <el-tab-pane label="基本信息">
          <el-form
            ref="formValidate"
            :rules="rules"
            :model="form"
            label-width="100px"
          >
            <el-row>
              <el-col :span="5">
                <el-form-item label="发券名称" prop="couponDirectName">
                  <el-input v-model="form.couponDirectName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5">
                <el-form-item label="券类型" prop="sendType">
                  <el-radio-group v-model="form.sendType">
                    <el-radio
                      :label="sendType.value"
                      v-for="sendType in sendTypeOptions"
                      :key="sendType.value"
                      >{{ sendType.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="发放目标" prop="sendTargetIds">
                  <el-input
                    v-model="form.sendTargetIds"
                    placeholder="发放目标，输入用户手机号，多个用户用英文逗号,分隔"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="短信通知" prop="smsNotify">
                  <el-radio-group v-model="form.smsNotify">
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5">
                <el-button type="primary" @click="addTableLine"
                  >选择优惠券</el-button
                >
              </el-col>
            </el-row>
            <el-row>
              <el-table
                :data="form.couponDirectLineList"
                row-key="couponId"
                style="width: 100%"
              >
                <el-table-column type="index" label="序号" width="60">
                </el-table-column>
                <el-table-column prop="couponName" label="券名称" width="200">
                  <template #default="scope">
                    <el-input
                      prop="couponName"
                      v-model="scope.row.couponName"
                      @keyup.enter="showItemTable(scope.row)"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="couponAmount" label="券面额" width="100">
                </el-table-column>
                <el-table-column
                  prop="couponLimit"
                  label="使用门槛"
                  width="100"
                >
                </el-table-column>
                <el-table-column prop="sendNum" label="发放数量" width="120">
                  <template #default="scope">
                    <el-input
                      prop="sendNum"
                      v-model="scope.row.sendNum"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="validityType"
                  label="有效期类型"
                  width="150"
                >
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.validityType"
                      placeholder="Select"
                    >
                      <el-option
                        v-for="item in validityTypeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="startDate"
                  label="开始日期/发券后N天"
                  width="260"
                >
                  <template #default="scope">
                    <el-date-picker
                      v-model="scope.row.startDate"
                      type="date"
                      placeholder="选择开始日期"
                      v-if="scope.row.validityType == 1"
                    />
                    <el-input
                      prop="afterDayNum"
                      v-model="scope.row.afterDayNum"
                      v-if="scope.row.validityType == 2"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="endDate"
                  label="结束日期/有效天数"
                  width="260"
                >
                  <template #default="scope">
                    <el-date-picker
                      v-model="scope.row.endDate"
                      type="date"
                      placeholder="选择结束日期"
                      v-if="scope.row.validityType == 1"
                    />
                    <el-input
                      prop="validDayNum"
                      v-model="scope.row.validDayNum"
                      v-if="scope.row.validityType == 2"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column>
                  <template #default="scope">
                    <el-button
                      type="danger"
                      @click="handleDeleteLine(scope.$index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>

    <CouponTable ref="couponTable" @onClick="handleClickCoupon"></CouponTable>
  </div>
</template>

<script setup name="CouponDirect">
import {
  pageCouponDirect,
  selectCouponDirectById,
  addCouponDirect,
  updateCouponDirect,
  deleteCouponDirect,
  sendCoupon,
} from "@/api/couponDirect";
import CouponTable from "@/components/common/CouponTable.vue";
import { ElMessageBox } from "element-plus";
import { ElMessage } from "element-plus";
import { ref, onMounted } from "vue";
import { formatTableColumnDate } from "@/utils/dateUtil";

let couponTable = ref();
let formValidate = ref();
let showEdit = ref(false);
let isEdit = ref(true);
let query = ref({ size: 10, current: 0, total: 1 });
let form = ref({
  sendType: 1,
  smsNotify: 0,
  couponDirectLineList: [],
});
let tableData = ref([]);
let rules = ref({
  couponDirectName: [
    { required: true, message: "请输入发券名称", trigger: "blur" },
  ],
  sendType: [{ required: true, message: "请选择发放类型", trigger: "blur" }],
  smsNotify: [
    { required: true, message: "请选择是否启用短信通知", trigger: "blur" },
  ],
});
let sendTypeOptions = ref([
  { label: "按标签", value: 1 },
  { label: "指定手机号", value: 2 },
]);
let validityTypeOptions = ref([
  { label: "指定日期", value: 1 },
  { label: "指定周期", value: 2 },
]);

function resetForm() {
  form.value = {
    sendType: 1,
    smsNotify: 0,
    couponDirectLineList: [],
  };
}
function currentChange(current) {
  query.value.current = current;
  loadData();
}
function loadData() {
  pageCouponDirect(query.value)
    .then((res) => {
      query.value.size = res.data.size;
      query.value.current = res.data.current;
      query.value.total = res.data.total;
      tableData.value = res.data.records;
    })
    .catch((err) => {
      console.log(err);
    });
}
function backTable() {
  resetForm();
  showEdit.value = false;
}
function handleView(row) {
  selectCouponDirectById(row.couponDirectId)
    .then((res) => {
      showEdit.value = true;
      isEdit.value = false;
      form.value = JSON.parse(JSON.stringify(res.data));
    })
    .catch((err) => {
      console.log(err);
    });
}
function handleUpdate(row) {
  selectCouponDirectById(row.couponDirectId)
    .then((res) => {
      form.value = res.data;
      showEdit.value = true;
      isEdit.value = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
function handleCreate() {
  showEdit.value = true;
  isEdit.value = true;
}
function handleDelete(row) {
  ElMessageBox.confirm("此操作将永久删除该记录, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteCouponDirect(row.couponDirectId)
        .then((res) => {
          ElMessage.success("删除成功");
          currentChange(1);
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch((err) => {
      ElMessage.message({
        type: "info",
        message: "取消删除",
      });
    });
}
function handleSendCoupon(row) {
  ElMessageBox.confirm("是否开始发放？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      sendCoupon(row.couponDirectId)
        .then((res) => {
          ElMessage.success("操作成功");
          currentChange(1);
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch((err) => {
      ElMessage.message({
        type: "info",
        message: "取消操作",
      });
    });
}
function submitForm() {
  form.value.couponDirectLineList = form.value.couponDirectLineList.filter(
    (line) => line.couponId
  );
  formValidate.value.validate((valid) => {
    if (valid) {
      if (form.value.couponDirectId != null) {
        updateCouponDirect(form.value)
          .then((res) => {
            showEdit.value = false;
            resetForm();
            ElMessage.success("修改成功");
            loadData();
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        addCouponDirect(form.value)
          .then((res) => {
            showEdit.value = false;
            resetForm();
            ElMessage.success("保存成功");
            loadData();
          })
          .catch((err) => {
            console.log(err);
          });
      }
    }
  });
}
function getMainImage(img) {
  return img ? img.split(",").map(String)[0] : "";
}
function showItemTable(row) {
  couponTable.value.dialogTableVisible = true;
}
function addTableLine() {
  form.value.couponDirectLineList.push({});
  console.log(form.value.couponDirectLineList);
}
function handleDeleteLine(index) {
  form.value.couponDirectLineList.splice(index, 1);
}
function handleClickCoupon(selectionCoupons) {
  couponTable.value.dialogTableVisible = false;
  selectionCoupons.forEach((coupon) => {
    var filterCoupon = form.value.couponDirectLineList.filter(
      (element) => element.couponId === coupon.couponId
    );
    if (filterCoupon.length == 0) {
      coupon.sendNum = 0;
      coupon.validityType = 1;
      form.value.couponDirectLineList.splice(
        form.value.couponDirectLineList.length - 1,
        0,
        coupon
      );

      console.log(form.value.couponDirectLineList);
    }
  });
}

onMounted(() => {
  loadData();
});
</script>

<style></style>
